package com.ysstech.common.service;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.entity.Role;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.mapper.DicvalueMapper;
import com.ysstech.common.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

@Slf4j
@Configuration
public class DicvalueService extends ServiceImpl<DicvalueMapper, Dicvalue> {

    @Autowired
    private RedisCacheManager redisCacheManager;
    public static String YSS_DICINFO = "YSS_DICINFO"; //字典数据缓存key


    public PageBean<Dicvalue> queryAllDicValue(Dicvalue dicvalue, PageBean pageBean) throws Exception {
        QueryWrapper<Dicvalue> wrapper = this.getQueryWrapper(dicvalue);
        IPage pageDicvalue = this.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), wrapper);
        this.switchedListDicvalue(pageDicvalue.getRecords());
        return new PageBean<>(pageDicvalue);
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    public List<Dicvalue> switchedListDicvalue(List<Dicvalue> list) throws Exception {
        return list;
    }

    /**
     * 查询条件
     *
     * @param dicvalue
     * @return
     * @throws Exception
     */
    private QueryWrapper<Dicvalue> getQueryWrapper(Dicvalue dicvalue) throws Exception {
        QueryWrapper<Dicvalue> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("ADD_TIME");
        if (null == dicvalue) {
            return wrapper;
        }
        if (StringUtils.isNotBlank(dicvalue.getSelCode())) {
            wrapper.like("CODE", dicvalue.getSelCode());
        }
        if (StringUtils.isNotBlank(dicvalue.getSelName())) {
            wrapper.like("NAME", dicvalue.getSelName());
        }
        if (StringUtils.isNotBlank(dicvalue.getStrStatus())) {
            List<Integer> list = JSONArray.parseArray(dicvalue.getStrStatus(), Integer.class);
            if (!CollectionUtils.isEmpty(list) && null != list.get(0)) {
                wrapper.in("STATUS", list);
            }
        }
        return wrapper;
    }

    /**
     * 查询参数缓存信息
     *
     * @param code
     * @return
     * @throws Exception
     */
    public List<Dicvalue> getCacheDicValueList(String code) throws Exception {
        List<Dicvalue> listdic = null;
        Map<String, List<Dicvalue>> mapdic = new HashMap<>();
        if (StringUtils.isBlank(code)) {
            throw new BusinessException("获取字典对应的信息失败，请稍后重试！");
        }
        //緩存信息有
        if (redisCacheManager.exists(YSS_DICINFO)) {
            String json = (String) redisCacheManager.getCache(YSS_DICINFO);
            List<Dicvalue> listall = JSONArray.parseArray(json, Dicvalue.class);
            List<Dicvalue> list = null;
            for (Dicvalue dicvalue : listall) {
                if (!code.equals(dicvalue.getCode())) {
                    continue;
                }
                // 包含code,就取出来添加一个
                if (mapdic.containsKey(dicvalue.getCode())) {
                    list = mapdic.get(dicvalue.getCode());
                    list.add(dicvalue);
                } else {
                    list = new ArrayList<>();
                    list.add(dicvalue);
                    mapdic.put(dicvalue.getCode(), list);
                }
            }
        } else {
            mapdic = this.getDicInfoMap();
        }
        if (null != mapdic && mapdic.size() > 0) {
            listdic = mapdic.get(code);
        }
        if (CollectionUtils.isEmpty(listdic)) {
            log.error("没有获取到" + code + "对应的参数信息");
            return listdic;
        }
        return listdic;
    }

    /**
     * 查询参数缓存信息
     * 返回的是value对应showmsg
     *
     * @param code
     * @return
     * @throws Exception
     */
    public Map<String, String> getCacheDicValueMap(String code) throws Exception {
        List<Dicvalue> listdic = null;
        Map<String, List<Dicvalue>> mapdic = new HashMap<>();
        if (StringUtils.isBlank(code)) {
            throw new BusinessException("获取字典对应的信息失败，请稍后重试！");
        }
        //緩存信息有
        if (redisCacheManager.exists(YSS_DICINFO)) {
            String json = (String) redisCacheManager.getCache(YSS_DICINFO);
            List<Dicvalue> listall = JSONArray.parseArray(json, Dicvalue.class);
            List<Dicvalue> list = null;
            for (Dicvalue dicvalue : listall) {
                if (!code.equals(dicvalue.getCode())) {
                    continue;
                }
                // 包含code,就取出来添加一个
                if (mapdic.containsKey(dicvalue.getCode())) {
                    list = mapdic.get(dicvalue.getCode());
                    list.add(dicvalue);
                } else {
                    list = new ArrayList<>();
                    list.add(dicvalue);
                    mapdic.put(dicvalue.getCode(), list);
                }
            }
        } else {
            mapdic = this.getDicInfoMap();
        }
        if (null != mapdic && mapdic.size() > 0) {
            listdic = mapdic.get(code);
        }
        if (CollectionUtils.isEmpty(listdic)) {
            log.error("没有获取到" + code + "对应的参数信息");
            return null;
        }
        Map<String, String> map = new HashMap<>();
        for (Dicvalue dicvalue : listdic) {
            map.put(dicvalue.getValue(), dicvalue.getShowmsg());
        }
        return map;
    }


    /**
     * 获取所有字典值信息
     *
     * @return
     */
    private Map<String, List<Dicvalue>> getDicInfoMap() {
        List<Dicvalue> list = null;
        QueryWrapper<Dicvalue> wrapper = new QueryWrapper<>();
        wrapper.eq("STATUS", 1); //状态启用的
        wrapper.orderByAsc("SEQUENCE");
        wrapper.orderByDesc("VALUE");
        List<Dicvalue> listall = this.list(wrapper); //所有字典值
        Map<String, List<Dicvalue>> mapDicInfo = new HashMap<>();
        for (Dicvalue dicvalue : listall) {
            // 包含code,就取出来添加一个
            if (mapDicInfo.containsKey(dicvalue.getCode())) {
                list = mapDicInfo.get(dicvalue.getCode());
                list.add(dicvalue);
            } else {
                list = new ArrayList<>();
                list.add(dicvalue);
                mapDicInfo.put(dicvalue.getCode(), list);
            }
        }
        redisCacheManager.putCache(YSS_DICINFO, JSONObject.toJSONString(listall));
        return mapDicInfo;
    }

    /**
     * 获取所有code
     *
     * @return
     */
    public Map<String, String> queryDicValueMap(String ftype) {
        QueryWrapper<Dicvalue> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(ftype)) {
            wrapper.eq("FTYPE", ftype);
        }
        wrapper.select("CODE,NAME").groupBy("CODE");
        List<Dicvalue> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        for (Dicvalue dicvalue : list) {
            map.put(dicvalue.getCode(), dicvalue.getName());
        }
        return map;
    }

    /**
     * 获取所有code
     *
     * @return
     */
    public List<Dicvalue> queryDicValueList(String ftype) {
        if (StringUtils.isBlank(ftype)) {
            return null;
        }
        QueryWrapper<Dicvalue> wrapper = new QueryWrapper<>();
        //wrapper.select("CODE,NAME,VALUE,SHOWMSG").groupBy("CODE");
        wrapper.eq("FTYPE", ftype);
        List<Dicvalue> list = this.list(wrapper);
        return list;
    }

    /**
     * 通过值获取显示信息
     *
     * @param code
     * @param value
     * @return
     */
    public String getDicShowmsg(String code, String value) throws Exception {
        Map<String, String> map = this.getCacheDicValueMap(code);
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        return map.get(value);
    }

    /**
     * 通过显示信息获取对应值
     *
     * @param code
     * @param showmsg
     * @return
     */
    public String getDicValue(String code, String showmsg) throws Exception {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(showmsg)) {
            return null;
        }
        Map<String, String> map = this.getCacheDicValueMap(code);
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (null == entry) {
                continue;
            }
            if (showmsg.equals(entry.getValue())) {
                return entry.getKey();
            }
        }
        return null;
    }

    /**
     * 查询一个字典的最大值
     *
     * @param code
     * @return
     */
    public String getMaxValue(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        QueryWrapper<Dicvalue> wrapper = new QueryWrapper<>();
        wrapper.select("MAX(VALUE) AS VALUE");
        wrapper.eq("CODE", code);
        Dicvalue dicvalue = this.getOne(wrapper);
        if (null == dicvalue || StringUtils.isBlank(dicvalue.getValue())) {
            return null;
        }
        return dicvalue.getValue();
    }
}
